package com.uzai.console.service.profit.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.profit.regrewardrule.RegRewardRuleIdDto;
import com.uzai.console.dto.profit.regrewardrule.RegRewardRuleInfoDto;
import com.uzai.console.dto.profit.regrewardrule.RegRewardRuleQuery;
import com.uzai.console.dto.sysplugin.SysPluginQuery;
import com.uzai.console.entity.InviteRewardRule;
import com.uzai.console.entity.NormalRewardRule;
import com.uzai.console.entity.RegRewardRule;
import com.uzai.console.mapper.InviteRewardRuleMapper;
import com.uzai.console.mapper.RegRewardRuleMapper;
import com.uzai.console.mapper.SysPluginMapper;
import com.uzai.console.service.profit.RegRewardRuleService;
import com.uzai.console.vo.profit.regrewardrule.RegRewardRuleInfoVo;
import com.uzai.console.vo.sysplugin.SysPluginVo;
import com.uzai.console.web.profit.PriRewardRuleContoller;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/***
 * @author liuqi
 * @date 2021年09月01日 19:26
 */
@Service
public class RegRewardRuleServiceImpl implements RegRewardRuleService {

    private Logger logger = LoggerFactory.getLogger(PriRewardRuleContoller.class);

    @Autowired
    private RegRewardRuleMapper regRewardRuleMapper;
    @Autowired
    private InviteRewardRuleMapper inviteRewardRuleMapper;
    @Autowired
    private SysPluginMapper sysPluginMapper;

    /**
     * 分页查询奖励方案列表
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param regRewardRuleQuery
     * @return null
     */
    public Page<RegRewardRuleInfoVo> findRegRewardRuleList(RegRewardRuleQuery regRewardRuleQuery){
        //新建返回到页面的LIST对象
        List<RegRewardRuleInfoVo> regRewardRuleInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<RegRewardRule> page = new Page<>();
        regRewardRuleQuery.convert(page);
        List<RegRewardRule> regRewardRuleList = regRewardRuleMapper.findByList(page, regRewardRuleQuery);

        if(regRewardRuleList != null){
            for (RegRewardRule regRewardRule : regRewardRuleList){
                RegRewardRuleInfoVo regRewardRuleInfoVo = new RegRewardRuleInfoVo();
                BeanUtils.copyProperties(regRewardRule, regRewardRuleInfoVo);
                try {
                    JSONObject dataObject = JSONObject.parseObject(regRewardRule.getData());
                    if(dataObject != null){
                        String inviteRewardId = dataObject.getString("invite_reward_id");
                        if(StringUtils.isNotBlank(inviteRewardId)){
                            InviteRewardRule inviteRewardRule = inviteRewardRuleMapper.selectById(Long.valueOf(inviteRewardId), regRewardRuleQuery.getMerId());
                            if(inviteRewardRule != null){
                                regRewardRuleInfoVo.setInviteRewardRuleName(inviteRewardRule.getName());
                            }
                        }
                    }
                }catch (Exception e){
                    logger.error("------invite_reward_id is not exist");
                }
                regRewardRuleInfoVoList.add(regRewardRuleInfoVo);
            }
        }

        //返回到页面分页对象
        Page<RegRewardRuleInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(regRewardRuleInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询奖励方案详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param regRewardRuleIdDto
     * @return null
     */
    public RegRewardRuleInfoVo findRegRewardRuleInfo(RegRewardRuleIdDto regRewardRuleIdDto){
        if(regRewardRuleIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        RegRewardRule regRewardRule = regRewardRuleMapper.selectById(regRewardRuleIdDto.getId(), regRewardRuleIdDto.getMerId());

        if(regRewardRule == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该奖励方案不存在");
        }

        RegRewardRuleInfoVo regRewardRuleInfoVo =  new RegRewardRuleInfoVo();

        BeanUtils.copyProperties(regRewardRule, regRewardRuleInfoVo);

        return regRewardRuleInfoVo;
    }

    /**
     * 添加奖励方案详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param regRewardRuleInfoDto
     * @return null
     */
    public void addRegRewardRule(RegRewardRuleInfoDto regRewardRuleInfoDto){
        if(StringUtils.isBlank(regRewardRuleInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "奖励方案名称不能为空");
        }
        if(StringUtils.isBlank(regRewardRuleInfoDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "奖励方案数据不能为空");
        }

        RegRewardRule regRewardRule_name = regRewardRuleMapper.selectByNameAndMerId(regRewardRuleInfoDto.getName(), regRewardRuleInfoDto.getMerId());
        if(regRewardRule_name != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "分佣规则名称重复");
        }

        RegRewardRule regRewardRule =  new RegRewardRule();
        BeanUtils.copyProperties(regRewardRuleInfoDto, regRewardRule);

        Integer now = DateUtil.getNowTime();
        regRewardRule.setId(IdWorker.getId());
        regRewardRule.setCreateTime(now);
        regRewardRule.setUpdateTime(now);
        regRewardRuleMapper.insert(regRewardRule);
    }

    /**
     * 修改奖励方案详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param regRewardRuleInfoDto
     * @return null
     */
    @Transactional
    public void updateRegRewardRule(RegRewardRuleInfoDto regRewardRuleInfoDto){

        if(regRewardRuleInfoDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        if(StringUtils.isBlank(regRewardRuleInfoDto.getName())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "奖励方案名称不能为空");
        }
        if(StringUtils.isBlank(regRewardRuleInfoDto.getData())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "奖励方案数据不能为空");
        }

        RegRewardRule regRewardRule = regRewardRuleMapper.selectById(regRewardRuleInfoDto.getId(), regRewardRuleInfoDto.getMerId());

        if(regRewardRule == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此奖励方案不存在");
        }

        //验证新名字是否已经存在
        if(!regRewardRule.getName().equals(regRewardRuleInfoDto.getName())){ //表示修改了名称
            //验证新名称是否存在
            RegRewardRule regRewardRule_name = regRewardRuleMapper.selectByNameAndMerId(regRewardRuleInfoDto.getName(), regRewardRuleInfoDto.getMerId());
            if(regRewardRule_name != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "分佣规则名称重复");
            }
        }

        regRewardRule.setName(regRewardRuleInfoDto.getName());
        regRewardRule.setData(regRewardRuleInfoDto.getData());
        regRewardRule.setUpdateTime(DateUtil.getNowTime());

        regRewardRuleMapper.update(regRewardRule);

    }

    /**
     * 删除奖励方案详情
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param regRewardRuleIdDto
     * @return null
     */
    public void deleteRegRewardRule(RegRewardRuleIdDto regRewardRuleIdDto){
        if(regRewardRuleIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        //判断该奖励方案是否已经在推广裂变插件中配置
        SysPluginQuery sysPluginQuery = new SysPluginQuery();
        sysPluginQuery.setMerId(regRewardRuleIdDto.getMerId());
        sysPluginQuery.setData(String.valueOf(regRewardRuleIdDto.getId()));
        List<SysPluginVo> sysPluginList = sysPluginMapper.findByList(sysPluginQuery);
        if(sysPluginList != null && sysPluginList.size() > 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该奖励方案已经在配置方案被占用，不能删除");
        }

        regRewardRuleMapper.deleteById(regRewardRuleIdDto.getId(), regRewardRuleIdDto.getMerId());
    }


}
